package com.cmse.util;

import java.util.Calendar;

import org.apache.log4j.Logger;

import com.cmse.constant.GlobalConstants;

/**
 * @author wulibin, exceptsky@gmail.com, 2012-3-15 下午5:42:37
 * 
 */
public class TokenUtil {
	private static Logger logger = Logger.getLogger(TokenUtil.class);
	 
	public static String makeToken(String target){
		Calendar calendar = Calendar.getInstance();
		return makeTokenWithTimeStamp(target, String.valueOf(calendar.getTimeInMillis()));
	}
	
	
	public static boolean checkToken(String target, String token){
		try{
			String tags[] = token.split("-");
			String timestamp = new String(EncryptionUtil.getFromBASE64(tags[1]));
			Calendar calendarNow = Calendar.getInstance();
			Calendar calendarPast = Calendar.getInstance();
			calendarPast.setTimeInMillis(Long.valueOf(timestamp));
			calendarPast.add(Calendar.DATE, 7);	// 超过7天后过期
			if(calendarNow.after(calendarPast)){
				return false;
			}
			
			if(token.equals(makeTokenWithTimeStamp(target, timestamp))){
				return true;
			}else{
				return false;
			}
		}catch (Exception e) {
			logger.error(e);
			return false;
		}
	}
	
	private static String makeTokenWithTimeStamp(String target, String timestamp){
		String timestampBs64 = EncryptionUtil.getBASE64(timestamp.getBytes());
		String targetBs64 = EncryptionUtil.getBASE64(target.getBytes());
		String tokenMd5 = EncryptionUtil.encodeMD5(GlobalConstants.SECURITY_KEY +  target + timestampBs64);
		
		return targetBs64 +"-"+ timestampBs64 +"-"+ tokenMd5;
	}
}
